package com.learn.eduuserboot.until;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.Random;
/**
 * @ClassName: OssUtil    用户头像更新到  bucket
 * @Description:
 * @Date: 2021/11/12 14:32
 */
@Component
public class OosUtil
{
    //protected static final Logger log = LoggerFactory.getLogger(OssUtil.class);

    //阿里云API的外网域名
    @Value("${aliyun.oos.oss_endpoint}")
    private String endpoint;

    //阿里云API的密钥Access Key ID
    @Value("${aliyun.oos.accessKeyId}")
    private String accessKeyId;


    //阿里云API的密钥Access Key Secret
    @Value("${aliyun.oos.accessKeySecret}")
    private String accessKeySecret;


    //阿里云API的bucket名称
    @Value("${aliyun.oos.oss_bucketName}")
    private String bucketName;

    //阿里云API的文件夹名称
    @Value("${aliyun.oos.oss_folder}")
    private String filedir;



    /**
     * 上传图片
     *
     * @param file
     * @return
     */
    public String uploadImg2Oss(MultipartFile file)
    {
        if (file.getSize() > 1024 * 1024 * 60)
        {
            return "图片太大";//RestResultGenerator.createErrorResult(ResponseEnum.PHOTO_TOO_MAX);
        }
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        Random random = new Random();
        String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
        try
        {
            InputStream inputStream = file.getInputStream();
            this.uploadFile2OSS(inputStream, name);
            return name;//RestResultGenerator.createSuccessResult(name);
        }
        catch (Exception e)
        {
            return "上传失败";//RestResultGenerator.createErrorResult(ResponseEnum.PHOTO_UPLOAD);
        }
    }

    /**
     * 上传图片获取fileUrl
     *
     * @param instream
     * @param fileName
     * @return
     */
    private String uploadFile2OSS(InputStream instream, String fileName)
    {
        String ret = "";
        try
        {
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            //上传文件

            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata);
            ret = putResult.getETag();
        }
        catch (IOException e)
        {
            System.out.println (e.getMessage()+ e);
        }
        finally
        {
            try
            {
                if (instream != null)
                {
                    instream.close();
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return ret;
    }

    public static String getcontentType(String FilenameExtension)
    {
        if (FilenameExtension.equalsIgnoreCase(".bmp"))
        {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif"))
        {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png"))
        {
            return "image/jpg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html"))
        {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt"))
        {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd"))
        {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt"))
        {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc"))
        {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml"))
        {
            return "text/xml";
        }
        return "image/jpg";
    }

    /**
     * 获取图片路径
     *
     * @param fileUrl
     * @return
     */
    public String getImgUrl(String fileUrl)
    {
        if (!StringUtils.isEmpty(fileUrl))
        {
            String[] split = fileUrl.split("/");
            String url = this.getUrl(this.filedir + split[split.length - 1]);
            return url;
        }
        return null;
    }

    /**
     * 获得url链接
     *
     * @param key
     * @return
     */
    public String getUrl(String key)
    {
        // 设置URL过期时间为10年 3600l* 1000*24*365*10
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        // 生成URL
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        if (url != null)
        {
            return url.toString();
        }
        return null;
    }




    public  String getPicSuffix(String img_path)
    {
        //如果图片地址为null或者地址中没有"."就返回""
        if (img_path == null || img_path.indexOf(".") == -1)
        {          return "";

        }
        return img_path.substring(img_path.lastIndexOf(".") + 1).trim().toLowerCase();
    }

    public OSSClient ossClient() {
        ClientConfiguration conf = new ClientConfiguration();
        conf.setSupportCname(true);
        CredentialsProvider credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
        OSSClient ossClient = new OSSClient(endpoint, credentialsProvider, conf);
        return ossClient;
    }

}
